﻿using System;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;
using Tau.Service;
using Tau.Web.Infrastructure;

namespace Tau.Web.Controllers
{
    public class ImageController : Controller
    {
        /// <summary>
        /// Based on the index of the image in the session list, returns a file content result to be rendered in browser
        /// </summary>
        /// <param name="id">image Id</param>
        /// <param name="type">thumbnail or large</param>
        /// <returns></returns>
        [CacheControl(HttpCacheability.ServerAndPrivate), HttpGet]
        public FileContentResult GetImage(int id, string type)
        {
            FileContentResult returnFile = null;

            var imageCacheId = string.Format("image{0}-{1}", id, type);
            Model.Image imageToReturn = null;

			if (HttpContext.Cache[imageCacheId] == null)
			{
                var svc = new TauService();
                imageToReturn = svc.GetImage(id);
                
                if (imageToReturn != null)
                {
                    HttpContext.Cache.Insert(imageCacheId, imageToReturn, null, DateTime.Now.AddMinutes(30), Cache.NoSlidingExpiration);
                }
			}
			else
			{
			    imageToReturn = (Model.Image)HttpContext.Cache[imageCacheId];
			}

            if (imageToReturn != null)
            {
                var imageBinary = type == "thumbnail" ? imageToReturn.ThumbnailImage : imageToReturn.LargeImage;

                returnFile = new FileContentResult(imageBinary, string.Format("image/{0}", imageToReturn.FileName.Substring(imageToReturn.FileName.IndexOf(".") + 1)));
            }

            return returnFile;
        }

    }
}
